import os
from flask import Flask, g

from applications.common.script import init_script
from applications.extensions import init_plugs
from applications.view import init_view
from applications.configs import config


def create_app(config_name=None):
    app = Flask(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

    if not config_name:
        # 尝试从本地环境中读取
        config_name = os.getenv('FLASK_CONFIG', 'development')

    # 引入数据库配置
    app.config.from_object(config[config_name])

    # 注册各种插件
    init_plugs(app)

    # 注册路由
    init_view(app)

    # 注册命令
    init_script(app)

    if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
        logo()

    app.debug = True

    SCENE_ADDRESS = os.getenv('SCENE_ADDRESS') or '127.0.0.1'
    SCENE_PORT = os.getenv('SCENE_PORT') or '10088'

    COURSE_ADDRESS = os.getenv('COURSE_ADDRESS') or '127.0.0.1'
    COURSE_PORT = os.getenv('COURSE_PORT') or '8000'
    COURSE_TOKEN = os.getenv('COURSE_TOKEN') or ''

    EMERGENCY_ADDRESS = os.getenv('EMERGENCY_ADDRESS') or '127.0.0.1'
    EMERGENCY_PORT = os.getenv('EMERGENCY_PORT') or '35000'

    app.config['SCENE_URL'] = 'http://' + SCENE_ADDRESS + ':' + SCENE_PORT
    app.config['EMERGENCY_URL'] = 'http://' + EMERGENCY_ADDRESS + ':' + EMERGENCY_PORT
    app.config['COURSE_URL'] = 'http://' + COURSE_ADDRESS + ':' + COURSE_PORT
    app.config['COURSE_TOKEN'] = COURSE_TOKEN


    return app


def logo():
    print('''
 ██████             ██      ██                                   
░█░░░░██           ░██     ░██           ██████  ██████   ██   ██
░█   ░██   █████   ░██     ░██  ██████  ░██░░░██░██░░░██ ░░██ ██ 
░██████   ██░░░██  ░██████████ ░░░░░░██ ░██  ░██░██  ░██  ░░███  
░█░░░░ ██░███████  ░██░░░░░░██  ███████ ░██████ ░██████    ░██   
░█    ░██░██░░░░   ░██     ░██ ██░░░░██ ░██░░░  ░██░░░     ██    
░███████ ░░██████  ░██     ░██░░████████░██     ░██       ██     
░░░░░░░   ░░░░░░   ░░      ░░  ░░░░░░░░ ░░      ░░       ░░      


    ''')
